package com.dalongxin.work.page;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dalongxin.work.BuildConfig;
import com.dalongxin.work.Constants;
import com.dalongxin.work.R;
import com.dalongxin.work.data.User;
import com.dalongxin.work.utils.HttpUtil;
import com.dalongxin.work.utils.StatusBarUtil;
import com.dalongxin.work.utils.ToastUtil;
import com.dalongxin.work.utils.Utils;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 登录界面
 * @author Yao
 */
@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity implements OnClickListener,
        OnFocusChangeListener, OnCheckedChangeListener {

    private static final String TAG = LoginActivity.class.getSimpleName();

    public static LoginActivity instance;
    private User account;
    private String loginName;
    private String password;
    private String smscode;
    @ViewInject(R.id.tool_bar)
    private Toolbar toolbar;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.input_phone)
    private EditText mUsernameEdit;
    @ViewInject(R.id.input_password)
    private EditText mPasswordEdit;
    @ViewInject(R.id.login)
    private Button loginBtn;
    @ViewInject(R.id.login_forgetPwd)
    private TextView forgetPwd;
    @ViewInject(R.id.login_getPwd)
    private TextView login_getPwd;
    @ViewInject(R.id.show_password)
    private ImageView show_password;
    @ViewInject(R.id.clear_username)
    private RelativeLayout clearUserName;
    @ViewInject(R.id.is_remarkPwd)
    private CheckBox remarkPwd;
    @ViewInject(R.id.login_scroll)
    private ScrollView login_scroll;
    @ViewInject(R.id.login_inner)
    private LinearLayout login_inner;
    @ViewInject(R.id.radio1)
    private RadioButton radio1;
    @ViewInject(R.id.divider)
    private View radioDivider;
    @ViewInject(R.id.radio2)
    private RadioButton radio2;// 密码登录、验证码登录
    @ViewInject(R.id.getCheckCode)
    private LinearLayout getCheckCode;
    private boolean isShowPass = false;

    @Override
    protected void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        instance = this;
        x.view().inject(this);
        StatusBarUtil.setPaddingSmart(this, toolbar);
        StatusBarUtil.darkMode(this, false);
        initViews();
        initData();
    }

    /**
     * 初始化布局
     */
    private void initViews() {
        radio1.setOnCheckedChangeListener(this);
        radio2.setOnCheckedChangeListener(this);
        clearUserName.setOnClickListener(this);
        show_password.setOnClickListener(this);
        // 隐藏滚动条
        login_scroll.setVerticalScrollBarEnabled(false);
        forgetPwd.setOnClickListener(this);
        loginBtn.setOnClickListener(this);
        mPasswordEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_NULL) {
                    hideKeyboard(mPasswordEdit.getWindowToken());
                    return true;
                }
                return false;
            }
        });
        mUsernameEdit.setOnFocusChangeListener(this);
        mPasswordEdit.setOnFocusChangeListener(this);
        mUsernameEdit.setOnClickListener(this);
        mPasswordEdit.setOnClickListener(this);
        login_getPwd.setOnClickListener(this);

        titleText.setText("登录");
        radio2.performClick();
        radioDivider.setVisibility(View.GONE);
        radio1.setVisibility(View.GONE);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        String autoLogin = spUtils.getObject(Constants.Key.AutoLogin, String.class);
        if ("1".equals(autoLogin)) {
            User autoAccount = getDefaultAccount();
            if(autoAccount != null){
                mUsernameEdit.setText(autoAccount.getLoginName());
                mPasswordEdit.setText(autoAccount.getLoginPass());
                loginByPassword(autoAccount.getLoginName(), autoAccount.getLoginPass());
            }
        } else {
            account = getDefaultAccount();
            if (account != null) {
                mUsernameEdit.setText(account.getLoginName());
                mPasswordEdit.setFocusable(true);
                mPasswordEdit.setFocusableInTouchMode(true);
                mPasswordEdit.requestFocus();
                //TODO 需要删的
                autoGotoMain();
            }
            mUsernameEdit.addTextChangedListener(textWatcher);

            if (account != null) {
                remarkPwd.setChecked(true);
            /*
             * if(remarkPwd.isChecked()){
             * mPasswordEdit.setText(mApp.getSp().getString
             * ("password"+account.getLoginname(), "")); }
             */
            } else {
                remarkPwd.setChecked(true);
            }
        }

    }

    private void autoGotoMain() {
        showLoading();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                hideLoading();
                gotoMain();
            }
        }, 1500);
    }

    @Override
    public void onFocusChange(View arg0, boolean arg1) {
        if (arg1 && arg0 == mUsernameEdit) {
            inputListonerMethod();
            if (mUsernameEdit.getEditableText().toString().trim().length() > 0) {
                clearUserName.setVisibility(View.VISIBLE);
            }
        } else {
            clearUserName.setVisibility(View.GONE);
        }
    }

    // 登录模式
    private boolean flag = false;

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            if (buttonView.getId() == R.id.radio1) {
                /*
                 * if(account!=null){
                 * mPasswordEdit.setText(mApp.getSp().getString
                 * ("password"+account.getLoginname(), "")); }
                 */
                mPasswordEdit.setText("");
                mPasswordEdit
                        .setTransformationMethod(PasswordTransformationMethod
                                .getInstance());
                mPasswordEdit.setHint("输入您的密码");
                show_password.setBackgroundResource(R.mipmap.login_pass_nosee);
                show_password.setVisibility(View.VISIBLE);
                getCheckCode.setVisibility(View.GONE);
                flag = false;
            } else {
                mPasswordEdit
                        .setTransformationMethod(HideReturnsTransformationMethod
                                .getInstance());
                mPasswordEdit.setText("");
                mPasswordEdit.setHint("输入您收到的验证码");
                show_password.setVisibility(View.GONE);
                getCheckCode.setVisibility(View.VISIBLE);
                flag = true;
            }

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                login();
                break;
            case R.id.input_phone:
                inputListonerMethod();
                break;
            case R.id.input_password:
                inputListonerMethod();
                break;
            case R.id.login_forgetPwd:
                gotoReset();
                break;
            case R.id.login_getPwd:// 调用获取验证码的接口
                sendCode();
                break;
            case R.id.clear_username:
                mUsernameEdit.setText("");
                break;
            case R.id.show_password:
                if (!isShowPass) {
                    show_password.setBackgroundResource(R.mipmap.login_pass_see);
                    mPasswordEdit
                            .setTransformationMethod(HideReturnsTransformationMethod
                                    .getInstance());
                } else {
                    show_password.setBackgroundResource(R.mipmap.login_pass_nosee);
                    mPasswordEdit
                            .setTransformationMethod(PasswordTransformationMethod
                                    .getInstance());
                }
                isShowPass = !isShowPass;
                break;
        }
    }

    private void login() {
        Animation shake = AnimationUtils.loadAnimation(instance, R.anim.shake);
        loginName = mUsernameEdit.getEditableText().toString().trim();
        password = mPasswordEdit.getEditableText().toString().trim();
        smscode = mPasswordEdit.getEditableText().toString().trim();

        if (loginName.length() < 1) {
            mUsernameEdit.startAnimation(shake);
            ToastUtil.showShort(this, "请输入正确的帐号");
        } else if (TextUtils.isEmpty(password)) {
            mPasswordEdit.setText("");
            mPasswordEdit.startAnimation(shake);
            if (!flag) {
                ToastUtil.showShort(this, "请输入密码");
            } else {
                ToastUtil.showShort(this, "请输入验证码");
            }
        } else {
            if(!flag) {
                loginByPassword(loginName, password);
            }else {
                loginByCode(loginName, smscode);
            }
        }
    }

    private void sendCode() {
        Animation shake = AnimationUtils.loadAnimation(LoginActivity.this, R.anim.shake);
        String account = mUsernameEdit.getEditableText().toString().trim();
        if (!Utils.validetorPhone(account)) {
            mUsernameEdit.startAnimation(shake);
            ToastUtil.showShort(this, "请输入正确的手机号码！");
        } else {
            login_getPwd.setEnabled(false);
            HashMap<String, String> params = new HashMap<String, String>();
            showLoading();
            params.put("phone", account);
            HttpUtil.getInstance().post(false, Constants.url_getCode, params, new Callback.CommonCallback<JSONObject>() {
                @Override
                public void onSuccess(JSONObject response) {
                    if (response.optInt("ret") == 0) {
                        sendCodeSuccess();
                        getCheckCode.setBackgroundResource(R.color.transparent);
                        ToastUtil.showShort(response.optString("msg"));
                    } else {
                        login_getPwd.setEnabled(true);
                        login_getPwd.setText("获取验证码");
                        ToastUtil.showShort(response.optString("msg"));
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    login_getPwd.setEnabled(true);
                    login_getPwd.setText("获取验证码");
                    ToastUtil.showShort("获取失败");
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    login_getPwd.setEnabled(true);
                    login_getPwd.setText("获取验证码");
                    ToastUtil.showShort("取消");
                }

                @Override
                public void onFinished() {
                    hideLoading();
                }
            });
        }
    }

    private void loginByCode(String username, String smsCode) {
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("phone", username);
        params.put("code", smsCode);
        params.put("imei", Utils.getIMEI(this));
        params.put("knowChannel", "android_v" + BuildConfig.VERSION_NAME);
        HttpUtil.getInstance().post(false, Constants.url_phoneLogin, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                if (response.optInt("ret") == 0) {
                    String data = response.optJSONObject("data").toString();
                    User user = gson.fromJson(data, User.class);
                    onLoginSuccess(1, user);
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    private void loginByPassword(String username, String password) {
        showLoading();
        Map<String, String> params = new HashMap<>();
        params.put("phone", username);
        params.put("password", password);
        params.put("imei", Utils.getIMEI(this));
        params.put("knowChannel", "android_v" + BuildConfig.VERSION_NAME);
        HttpUtil.getInstance().post(false, Constants.base_url_api, params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                if (response.optInt("ret") == 0) {
                    String data = response.optJSONObject("data").toString();
                    User user = gson.fromJson(data, User.class);
                    onLoginSuccess(1, user);
                } else {
                    ToastUtil.showShort(response.optString("msg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideLoading();
            }
        });
    }

    private Timer timer;// 计时器
    int jishi = 60;

    public void sendCodeSuccess() {
        login_getPwd.setEnabled(false);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(jishi--);
            }
        }, 0, 1000);
    }

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what <= 0) {
                login_getPwd.setEnabled(true);
                login_getPwd.setText("重新获取");
                if (timer != null) {
                    timer.cancel();
                }
                jishi = 60;
            } else {
                login_getPwd.setText("(" + String.format("%02d", msg.what) + "秒)");
            }
        }

        ;
    };

    /**
     * 动态监听输入法是打开还是关闭
     */
    private void inputListonerMethod() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            scrollToBottom(login_scroll, login_inner);
        }
    }

    /**
     * 让ScrollView滑到底部
     *
     * @param scroll
     * @param inner
     */
    public void scrollToBottom(final View scroll, final View inner) {

        Handler mHandler = new Handler();

        mHandler.post(new Runnable() {
            public void run() {
                if (scroll == null || inner == null) {
                    return;
                }
                int offset = inner.getMeasuredHeight() - scroll.getHeight();
                if (offset < 0) {
                    offset = 0;
                } else if (offset == 0) {
                    scrollToBottom(login_scroll, login_inner);
                }

                scroll.scrollTo(0, offset);
            }
        });
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void afterTextChanged(Editable arg0) {
            if (login_getPwd.isEnabled() && login_getPwd.getText().equals("重新获取")) {
                login_getPwd.setText("获取验证码");
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            if (arg0.length() > 0) {
                clearUserName.setVisibility(View.VISIBLE);
            } else {
                clearUserName.setVisibility(View.GONE);
            }
        }
    };

    private void onLoginSuccess(int loginType, User user) {
        user.setLastLogin(1);
        user.setLoginTime(System.currentTimeMillis());
        user.setLoginType(loginType);
        try {
            setDefaultAccount(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            gotoMain();
        }
    }

    // Goto 注册页面
    private void gotoRegister() {
        /*Intent intent = new Intent(LoginActivity.this, RegisterNewActivity.class);
        startActivity(intent);*/
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    // Goto 忘记密码页面
    private void gotoReset() {
    }

    // Goto 主页面
    private void gotoMain() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    public void onDestroy() {
        super.onDestroy();
    }

}
